let goBackBtn = document.querySelector(".headerLeftBox img");
let headerMiddleBox = document.querySelectorAll(".headerMiddleBox div");
let list = document.querySelectorAll(".list");
let reimbursementDetail = document.querySelector(".reimbursementDetail");
let reimbursementDate = document.querySelector(".reimbursementDate");
let reimbursementTotal = reimbursementDetail.querySelector(".reimbursementTotal span");
let changeReimbursementInformation = document.querySelector(".changeReimbursementInformation");
let shade = document.querySelector(".shade");
let reimbursementBillBtn = document.querySelector(".reimbursementBill");
let noReimbursement = document.querySelector(".noReimbursement");

// 详细信息窗口
let amount = changeReimbursementInformation.querySelector(".amount");
let time = changeReimbursementInformation.querySelector(".time");
let unReiconsumeType = changeReimbursementInformation.querySelector(".consumeType");
let annotation = changeReimbursementInformation.querySelector(".remark");

// 获取修改报销金额窗口元素
let changehaveAppliedAmount = document.querySelector(".changehaveAppliedAmount");
let changeAmountBtn = changehaveAppliedAmount.querySelector("button");
let changeAmountInput = changehaveAppliedAmount.querySelector("input");
let errTips = changehaveAppliedAmount.querySelector(".errTips");

// 获取修改报销金额窗口元素
let changehaveAppliedInformation = document.querySelector(".changehaveAppliedInformation");
let reimbursementAmount = changehaveAppliedInformation.querySelector(".reimbursementAmount");
let reimbursementAmountDate = changehaveAppliedInformation.querySelector(".reimbursementTime");
let reiAmount = changehaveAppliedInformation.querySelector(".amount");
let reiConsumeType = changehaveAppliedInformation.querySelector(".consumeType");
let reiAnnotation = changehaveAppliedInformation.querySelector(".remark");
let reiTime = changehaveAppliedInformation.querySelector(".time");

let checkedList = [];
let titleChoose = 0;
let listHeight = 0;
let reimbursementDetailHeight = reimbursementDetail.scrollHeight;
let changehaveAppliedInformationHeight = changehaveAppliedInformation.scrollHeight;
let changeReimbursementInformationHeight = changeReimbursementInformation.scrollHeight;

createUnReimburseList();

// 绑定返回按钮事件
goBackBtn.addEventListener("click", () => {
  window.location.href = "./userMmt.html";
});

// 给标题绑定点击事件
headerMiddleBox.forEach((item) => {
  item.addEventListener("click", titleEvent);
});

// 修改报销金额点击事件
reimbursementTotal.addEventListener("click", changehaveAppliedAmountEvent);
document.addEventListener("click", checkedEvent);

// 点击报销事件
function reimbursementBill(e) {
  updateReimbursed(Number(reimbursementBillBtn.id), Number(reimbursementBillBtn.money));
  closeReimbursementWindow();
  createUnReimburseList();
}

// 点击标题事件
function titleEvent(e) {
  //重置选中信息
  checkedList.forEach((item) => {
    item.classList.remove("checkBoxChecked");
  });
  checkedList = [];
  closeReimbursementWindow();

  headerMiddleBox.forEach((item, index) => {
    item.classList.remove("choose");
    if (e.target == item) {
      titleChoose = index;
    }
  });
  e.target.classList.add("choose");
  changeListShow(e);
}

// 弹出报销弹窗
function showReimbursementWindow(e) {
  reimbursementBillBtn.id = e.target.parentElement.parentElement.id;
  if (!checkedList.length) {
    closeReimbursementWindow();
    return;
  }

  if (reimbursementDetail.style.bottom == "" || reimbursementDetail.style.bottom == "-100%") {
    list[titleChoose].style.marginBottom = `${reimbursementDetailHeight + 50}px`;
    reimbursementDetail.style.bottom = "0px";
    reimbursementDetail.style.zIndex = "20";
  }

  reimbursementDetail.money = Number(e.target.parentElement.nextElementSibling.textContent);
  reimbursementTotal.textContent = reimbursementDetail.money.toFixed(2);
  reimbursementBillBtn.money = reimbursementDetail.money;
  let reiDate = `${new Date().getFullYear()}-${new Date().getMonth() + 1}-${new Date().getDate()}`;
  reimbursementDate.textContent = reiDate;

  reimbursementBillBtn.addEventListener("click", reimbursementBill);
}

// 修改报销金额
function changehaveAppliedAmountEvent() {
  changehaveAppliedAmount.classList.add("show");
  shade.classList.add("show");
  changeAmountInput.placeholder = `${reimbursementDetail.money}`;
  changeAmountInput.value = reimbursementBillBtn.money.toFixed(2);
  errTips.classList.remove("errTipsShow");
  changeAmountInput.addEventListener("input", function () {
    if (Number(changeAmountInput.value) > Number(reimbursementDetail.money) || changeAmountInput.value == "") {
      errTips.classList.add("errTipsShow");
      changeAmountBtn.classList.add("buttonDisabled");
      changeAmountBtn.removeEventListener("click", changeAmountEvent);
    } else {
      errTips.classList.remove("errTipsShow");
      changeAmountBtn.classList.remove("buttonDisabled");
      changeAmountBtn.addEventListener("click", changeAmountEvent);
    }
  });
}

// 修改报销金额事件
function changeAmountEvent() {
  reimbursementBillBtn.money = Number(changeAmountInput.value);
  reimbursementTotal.textContent = Number(reimbursementBillBtn.money).toFixed(2);
  changehaveAppliedAmount.classList.remove("show");
  shade.classList.remove("show");
}

// 关闭报销弹窗
function closeReimbursementWindow() {
  reimbursementDetail.style.bottom = "-100%";
  reimbursementDetail.style.zIndex = "-10";
}

// 触发标题点击事件后，切换显示列表
function changeListShow(e) {
  headerMiddleBox.forEach((item, index) => {
    list[index].classList.remove("listShow");
    if (e.target == item) {
      titleChoose = index;
    }
  });
  list[titleChoose].classList.add("listShow");
  if (titleChoose == 0) {
    createUnReimburseList();
  } else {
    createReimburseList();
  }
}

// 生成未报销数据
async function createUnReimburseList() {
  let data = await getAllData();
  let unReimburseData = getUnReimburse(data);
  let unReimburseRes = dataGroup(unReimburseData);
  if (!unReimburseRes.length) {
    noReimbursement.classList.add("show");
  } else {
    noReimbursement.classList.remove("show");
  }

  // 渲染未报销列表
  createList(unReimburseRes);
}

// 生成已报销数据
async function createReimburseList() {
  let data = await getAllData();
  let reimburseData = getReimburse(data);
  let reimburseRes = dataGroup(reimburseData);
  if (!reimburseRes.length) {
    noReimbursement.classList.add("show");
  } else {
    noReimbursement.classList.remove("show");
  }
  createList(reimburseRes);
}

// 渲染列表
function createList(arr) {
  list[titleChoose].innerHTML = "";
  arr.forEach((item) => {
    let data = item.subList;
    let sum = 0;

    let ul = document.createElement("ul");

    data.forEach((item) => {
      sum += item.money;
      let li = document.createElement("li");
      let year = new Date(item.time).getFullYear();
      let month = new Date(item.time).getMonth() + 1;
      let date = new Date(item.time).getDate();
      let reimburseMoney = item.reimburseMoney;
      let punctuation = "/";
      if (!titleChoose) {
        reimburseMoney = "";
        punctuation = "";
      }

      li.innerHTML = `<div>
                        <span class="reimbursementCheckBox"></span>
                        <div>
                            <span>报销·<span>${item.consumeType}</span></span>
                            <div>
                                <span>${month}-${date}</span>
                                <span>${item.annotation}</span>
                            </div>
                        </div>
                    </div>
                    <span><span class="haveAppliedAmount">${reimburseMoney}<span>${punctuation}</span></span>${item.money.toFixed(2)}</span>`;
      li.addEventListener("click", showReimbursementInformation);
      li.money = item.money;
      li.time = `${year}-${month}-${date}`;
      li.consumeType = item.consumeType;
      li.annotation = item.annotation;
      li.reimburseMoney = item.reimburseMoney;
      li.id = item.id;
      li.reimburseTime = item.reimburseTime;
      ul.append(li);
    });
    
    let div = document.createElement("div");
    div.innerHTML = `<div class="month"><p>${item.date.slice(5)}</p>月</div>
                      <div class="total">总共:<p>${sum}</p>元</div>`
    ul.prepend(div)
    list[titleChoose].append(ul);
})
}

// 点击遮罩层隐藏弹窗
document.addEventListener("click", function (e) {
  if (!shade.contains(e.target)) return;
  changeReimbursementInformation.classList.remove("show");
  changehaveAppliedAmount.classList.remove("show");
  changehaveAppliedInformation.classList.remove("show");
  shade.classList.remove("show");
  list[titleChoose].style.marginBottom = `30px`;
});

// 已报销详情窗口
function haveAppliedInformation(money, date, consumeType, annotation, reimburseMoney, reimburseDate) {
  let year = new Date(reimburseDate).getFullYear();
  let month = new Date(reimburseDate).getMonth() + 1;
  let day = new Date(reimburseDate).getDate();
  time = `${year}-${month}-${day}`;
  reiAmount.textContent = money.toFixed(2);
  reiTime.textContent = date;
  reiConsumeType.textContent = consumeType;
  reiAnnotation.textContent = annotation;
  reimbursementAmount.textContent = reimburseMoney.toFixed(2);
  reimbursementAmountDate.textContent = time;

  changehaveAppliedInformation.classList.add("show");
  shade.classList.add("show");

  list[titleChoose].style.marginBottom = `${changehaveAppliedInformationHeight + 50}px`;
}

// 弹出详细信息窗口
function showReimbursementInformation(e) {
  if (e.target.classList.contains("reimbursementCheckBox")) return;

  if (titleChoose == 0) {
    ReimbursementInformation(this.money, this.time, this.consumeType, this.annotation);
  } else {
    haveAppliedInformation(this.money, this.time, this.consumeType, this.annotation, this.reimburseMoney, this.reimburseTime);
  }
}

// 未报销详情窗口
function ReimbursementInformation(money, date, consumeType, annotation) {
  amount.textContent = money.toFixed(2);
  time.textContent = date;
  unReiconsumeType.textContent = consumeType;
  annotation.textContent = annotation;
  shade.classList.add("show");
  changeReimbursementInformation.classList.add("show");
  list[titleChoose].style.marginBottom = `${changeReimbursementInformationHeight + 50}px`;
}

// 复选框选中事件
function checkedEvent(e) {
  if (!e.target.classList.contains("reimbursementCheckBox")) return;
  let index = checkedList.indexOf(e.target);
  if (index != -1) {
    checkedList[0].classList.remove("checkBoxChecked");
    checkedList = [];
  } else {
    if (checkedList[0]) {
      checkedList[0].classList.remove("checkBoxChecked");
    }
    checkedList[0] = e.target;
    e.target.classList.add("checkBoxChecked");
  }
  if (!titleChoose) {
    showReimbursementWindow(e);
  }
}
